﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace Puppy.ActorDb.Query
{
    public class ActorQueryProvider<TEntity> : IActorQueryProvider
        where TEntity : class
    {
        private readonly IActorSet<TEntity> _collection;

        public ActorQueryProvider(IActorSet<TEntity> collection)
        {
            _collection = Check.NotNull(collection, nameof(collection));
        }

        public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
        {
            return new ActorQueryable<TElement>(this, expression);
        }

        public IQueryable CreateQuery(Expression expression)
        {
            Check.NotNull(expression, nameof(expression));

            var elementType = expression.Type.GetSequenceElementType();

            try
            {
                return (IQueryable)Activator.CreateInstance(
                    typeof(ActorQueryable<>).MakeGenericType(typeof(TEntity), elementType),
                    new object[] { this, expression });
            }
            catch (TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
        }

        public TResult Execute<TResult>(Expression expression)
        {
            var result = Execute(expression);
            return (TResult)result;
        }

        public object Execute(Expression expression)
        {
            throw new NotImplementedException();
        }

        public Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }
    }
}
